package md.lanjing.com.module_deal_center.ui.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;

import com.lxh.baselibray.constant.ARouterConfig;
import com.lxh.baselibray.dialog.AlertDialog;
import com.lxh.baselibray.event.BusFactory;
import com.lxh.baselibray.mvp.MvpFragment;
import com.lxh.baselibray.util.ARouterUtils;
import com.lxh.baselibray.util.ObjectUtils;
import com.lxh.baselibray.util.SPUtils;
import com.lxh.baselibray.util.SizeUtils;
import com.lxh.baselibray.util.ToastUtils;
import com.lxh.baselibray.view.PswText;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import butterknife.BindView;
import butterknife.OnClick;


import com.lxh.baselibray.constant.Constant;
import com.lxh.baselibray.event.EventImpl;


import md.lanjing.com.module_deal_center.R;
import md.lanjing.com.module_deal_center.R2;
import com.lxh.baselibray.base.BaseResponce;
import md.lanjing.com.module_deal_center.contact.ConsignmentContact;
import md.lanjing.com.module_deal_center.ui.activity.OrderActivity;
import retrofit2.Response;

public class ConsignFragment extends MvpFragment<ConsignmentContact.ConsignmentPresent> implements ConsignmentContact.IConsignmentView {
    @BindView(R2.id.cb_weixin)
    CheckBox cbWeixin;
    @BindView(R2.id.cb_ali)
    CheckBox cbAli;
    @BindView(R2.id.cb_card)
    CheckBox cbCard;
    @BindView(R2.id.tv_select_coin_type)
    TextView tvSelectCoinType;
    @BindView(R2.id.et_number)
    EditText etNumber;
    @BindView(R2.id.et_per_price)
    EditText etPerPrice;
    @BindView(R2.id.tv_total_price)
    TextView tvTotalPrice;
    @BindView(R2.id.btn_consign)
    Button btnConsign;
    @BindView(R2.id.tv_remind)
    TextView tvReimind;
    @BindView(R2.id.tv_hand_fee)
    TextView tvHandFee;

    private int type = -1;

    int weChat = 0;
    int aliPay = 0;
    int bank = 0;
    String aliPngCode;
    String weixinPngCode;
    String bankNumber;
    @Override
    public void initData(Bundle savedInstanceState) {
        //检验用户是否上传收款方式
        checkReceiveType();
        //监听
        setListener();
    }

    private void setListener() {
        //选中收款方式监听
        cbWeixin.setOnCheckedChangeListener((buttonView, isChecked) -> {
            if (isChecked) {
                weChat = 1;
            } else {
                weChat = 0;
            }
        });
        cbAli.setOnCheckedChangeListener((buttonView, isChecked) -> {
            if (isChecked) {
                aliPay = 1;
            } else {
                aliPay = 0;
            }
        });
        cbCard.setOnCheckedChangeListener((buttonView, isChecked) -> {
            if (isChecked) {
                bank = 1;
            } else {
                bank = 0;
            }
        });

        etPerPrice.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                String number = etNumber.getText().toString();
                if (!ObjectUtils.isEmpty(number) && !ObjectUtils.isEmpty(s.toString())) {
                    tvTotalPrice.setText("寄售总价：" + Double.valueOf(number) * Double.valueOf(s.toString()) + "CNY");
                }else {
                    tvTotalPrice.setText("寄售总价：" + 0.0 + "CNY");
                }
            }
        });
        etNumber.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                String perPrice = etPerPrice.getText().toString();
                if (!ObjectUtils.isEmpty(s.toString())){
                    tvHandFee.setText("手续费:"+Double.valueOf(s.toString())*0.005+"CAWD");
                }else {
                    tvHandFee.setText("手续费:"+0.0+"CAWD");
                }
                if (!ObjectUtils.isEmpty(perPrice) && !ObjectUtils.isEmpty(s.toString())) {
                    tvTotalPrice.setText("寄售总价：" + Double.valueOf(perPrice) * Double.valueOf(s.toString()) + "CNY");
                }else {
                    tvTotalPrice.setText("寄售总价：" + 0.0 + "CNY");
                }
            }
        });
    }

    private void checkReceiveType() {
         aliPngCode = SPUtils.getString(Constant.ALI_PNG, null, context);
         weixinPngCode = SPUtils.getString(Constant.WEIXIN_PNG, null, context);
         bankNumber = SPUtils.getString(Constant.BANK_NUMBER, null, context);
        if (ObjectUtils.isEmpty(aliPngCode) && ObjectUtils.isEmpty(weixinPngCode) && ObjectUtils.isEmpty(bankNumber)) {
            tvReimind.setVisibility(View.VISIBLE);
        } else {
            tvReimind.setVisibility(View.GONE);
        }
        if (ObjectUtils.isEmpty(aliPngCode)) {
            cbAli.setVisibility(View.GONE);
        } else {
            cbAli.setVisibility(View.VISIBLE);
        }
        if (ObjectUtils.isEmpty(weixinPngCode)) {
            cbWeixin.setVisibility(View.GONE);
        } else {
            cbWeixin.setVisibility(View.VISIBLE);
        }
        if (ObjectUtils.isEmpty(bankNumber)) {
            cbCard.setVisibility(View.GONE);
        } else {
            cbCard.setVisibility(View.VISIBLE);
        }

    }

    @Override
    public int getLayoutId() {
        return R.layout.fragment_consign;
    }


    @OnClick({R2.id.tv_select_coin_type, R2.id.btn_consign, R2.id.tv_remind})
    public void onViewClicked(View view) {
        int i = view.getId();
        if (i == R.id.tv_select_coin_type) {
            showTypeDialog();//功能隐藏

        } else if (i == R.id.btn_consign) {
            String number = etNumber.getText().toString();
            String perPrice = etPerPrice.getText().toString();
            String coinTypeText = tvSelectCoinType.getText().toString();
            if (ObjectUtils.isEmpty(aliPngCode) && ObjectUtils.isEmpty(weixinPngCode) && ObjectUtils.isEmpty(bankNumber)) {
                showRemindDialog("您还未上传收款方式,去上传?", 1);
                return;
            }
            if (weChat == 0 && aliPay == 0 && bank == 0) {
                ToastUtils.showLongToast(context, "请至少选择一种收款方式");
                return;
            }
 if (type == -1) {
                    ToastUtils.showLongToast(context, "请选择币种");
                    return;
                }

            if (ObjectUtils.isEmpty(number)) {
                ToastUtils.showLongToast(context, "寄售数量不能为空");
                return;
            }
            if (ObjectUtils.isEmpty(perPrice)) {
                ToastUtils.showLongToast(context, "寄售单价不能为空");
                return;
            }
            String realName = SPUtils.getString(Constant.IS_REAL, null, context);
            if (ObjectUtils.isEmpty(realName)) {
                showRemindDialog("你还未实名认证,去认证?", 2);
                return;
            }
            showDealDialog("USDT", number, perPrice);//暂时只支持usdt

        } else if (i == R.id.tv_remind) {
            showRemindDialog("您还未上传收款方式,去上传?", 1);

        }
    }

    AlertDialog typeDialog = null;

    private void showTypeDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(context)
                .addDefaultAnimation()
                .setCancelable(true)
                .setContentView(R.layout.dialog_type_select)
                .fromBottom(true)
                .setWidthAndHeight(ViewGroup.LayoutParams.MATCH_PARENT, SizeUtils.dp2px(context, 80))
                .setOnClickListener(R.id.tv_one, v -> {
                    type = 1;
                    tvSelectCoinType.setText("USDT");
                    typeDialog.dismiss();
                }).setOnClickListener(R.id.tv_two, v -> {
                    type = 0;
                    tvSelectCoinType.setText("CAWD");
                    typeDialog.dismiss();
                });
        typeDialog = builder.create();
        typeDialog.show();
    }

    AlertDialog dealDialog = null;

    private void showDealDialog(String coinType, String num, String perPrice) {
        AlertDialog.Builder builder = new AlertDialog.Builder(context)
                .addDefaultAnimation()
                .setCancelable(true)
                .setContentView(R.layout.dialog_deal_pwd)
                .setWidthAndHeight(SizeUtils.dp2px(context, 279), SizeUtils.dp2px(context, 157))
                .setOnClickListener(R.id.tv_sure, v -> {
                    PswText psw = dealDialog.getView(R.id.pt_deal_pwd);
                    String dealPwd = psw.getPsw();
                    mPresent.addConsignmentOrder(context, weChat, aliPay, bank, coinType, Double.valueOf(num), Double.valueOf(perPrice), dealPwd);
                    dealDialog.dismiss();
                }).setOnClickListener(R.id.tv_cancle, v -> dealDialog.dismiss());
        dealDialog = builder.create();
        dealDialog.show();
    }

    AlertDialog remindDialog = null;
    private void showRemindDialog(String content,int toWhere) {
        AlertDialog.Builder builder = new AlertDialog.Builder(context)
                .addDefaultAnimation()
                .setCancelable(true)
                .setContentView(R.layout.dialog_reimind)
                .setText(R.id.tv_content, content)
                .setWidthAndHeight(SizeUtils.dp2px(context, 279), SizeUtils.dp2px(context, 157))
                .setOnClickListener(R.id.tv_sure, v -> {
                    if (toWhere==1){
                        ARouterUtils.jump(ARouterConfig.Mine_receive_money_type_act);
                    }else if (toWhere==2){
                        ARouterUtils.jump(ARouterConfig.Mine_real_name_authen_act);
                    }else {
                        startActivity(new Intent(context, OrderActivity.class));
                    }
                    remindDialog.dismiss();
                }).setOnClickListener(R.id.tv_cancle, v -> remindDialog.dismiss());
        remindDialog = builder.create();
        remindDialog.show();
    }

    @Override
    protected ConsignmentContact.ConsignmentPresent createPresent() {
        return new ConsignmentContact.ConsignmentPresent();
    }

    @Override
    public void getAddConsignmentOrderData(Response<BaseResponce> response) {
        if (response.body().getCode() == Constant.SUCCESS_CODE) {
            BusFactory.getBus().post(new EventImpl.ConsignEvent());
            showRemindDialog("寄售成功,去查看订单",3);
        } else {
            ToastUtils.showLongToast(context, response.body().getMsg());
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void upPayMent(EventImpl.PaymentEvent event){
        if (!ObjectUtils.isEmpty(event)){
            //上传收款方式成功
           checkReceiveType();
        }
    }

    @Override
    public boolean useEventBus() {
        return true;
    }
}
